package com.cyq.dascma.util;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * dingwen
 * 2021/4/3 21:51
 **/
public class DateTimeUtil {
    // 格式：中文星期
    private final static String[] FORMAT_WEEK_CHINESE_SIMPLE = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    // 格式：中文星期
    private final static String[] FORMAT_WEEK_CHINESE = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
    // 格式：英文格式简写
    private final static String[] FORMAT_WEEK_ENGLISH_SIMPLE = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    // 格式：英文全称
    private final static String[] FORMAT_WEEK_ENGLISH = {"Sun", " Mon", " Tue", " Wed", " Thu", " Fri", " Sat"};

    /**
     * 获取今日年份
     *
     * @return yyyy
     */
    public static String getCurrentYear() {
        return DateFormatUtils.format(new Date(), "yyyy");
    }

    /**
     * 获取今日月份
     *
     * @return MM
     */
    public static String getCurrentMonth() {
        return DateFormatUtils.format(new Date(), "MM");
    }

    /**
     * 获取今日日期
     *
     * @return dd
     */
    public static String getTodayDay() {
        return DateFormatUtils.format(new Date(), "dd");
    }


    /**
     * 返回年月
     *
     * @return yyyyMM
     */
    public static String getTodayChar6() {
        return DateFormatUtils.format(new Date(), "yyyyMM");
    }

    /**
     * 返回年月日
     *
     * @return yyyyMMdd
     */
    public static String getTodayChar8() {
        return DateFormatUtils.format(new Date(), "yyyyMMdd");
    }

    public static String getDateChar8(Date date) {
        return DateFormatUtils.format(date, "yyyyMMdd");
    }

    /**
     * 返回 年月日小时分
     *
     * @return yyyyMMddHHmm
     */
    public static String getTodayChar12() {
        return DateFormatUtils.format(new Date(), "yyyyMMddHHmm");
    }

    /**
     * 返回 年月日小时分秒
     *
     * @return yyyyMMddHHmmss
     */
    public static String getTodayChar14() {
        return DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
    }

    /**
     * 返回 年月日小时分秒 毫秒
     *
     * @return yyyyMMddHHmmssS
     */
    public static String getTodayChar17() {
        String dateString = DateFormatUtils.format(new Date(), "yyyyMMddHHmmssS");
        int length = dateString.length();

        if (length < 17) {
            String endStr = dateString.substring(14, length);
            int len = endStr.length();
            for (int i = 0; i < 3 - len; i++) {
                endStr = "0" + endStr;
            }
            dateString = dateString.substring(0, 14) + endStr;
        }
        return dateString;
    }

    /**
     * 返回本地系统当前时间戳
     *
     * @return
     */
    public static long getSysCurrentTimeMillis() {
        return System.currentTimeMillis();
    }

    /**
     * 日期格式转换
     *
     * @param timeMillis
     * @param format
     * @return
     */
    public static String convertTimeFormat(long timeMillis, String format) {
        return DateFormatUtils.format(timeMillis, format);
    }

    /**
     * 返回当前系统时间
     *
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getSystemTime() {
        Calendar theCa = Calendar.getInstance();
        theCa.setTime(new Date());
        return DateFormatUtils.format(theCa.getTime(), "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 返回当前系统时间
     *
     * @return yyyy -MM-dd HH:mm:ss
     */
    public static String getSysTime() {
        Calendar theCa = Calendar.getInstance();
        theCa.setTime(new Date());
        return DateFormatUtils.format(theCa.getTime(), "yyyyMMddHHmmss");
    }

    public static String getStrTimes(String dataStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String strTime = "";
        try {
            Date date = sdf.parse(dataStr);
            SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMddHHmmss");
            strTime = sdf3.format(date);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return strTime;
    }

    /**
     * 获取今天星期几
     *
     * @param type 默认值1:中文（周一）；2:中文（星期一）；3:英文缩写（Mon）;4:英文全称（Monday）
     * @return
     */
    public static String getWeekName(int type) {
        String strResult = " ";
        try {
            Calendar calendar = Calendar.getInstance();
            int intWeekNum = calendar.get(Calendar.DAY_OF_WEEK);
            intWeekNum = intWeekNum - 1;
            if (type == 1) {
                strResult = FORMAT_WEEK_CHINESE_SIMPLE[intWeekNum];
            } else if (type == 2) {
                strResult = FORMAT_WEEK_CHINESE[intWeekNum];
            } else if (type == 3) {
                strResult = FORMAT_WEEK_ENGLISH_SIMPLE[intWeekNum];
            } else if (type == 4) {
                strResult = FORMAT_WEEK_ENGLISH[intWeekNum];
            } else {
                strResult = FORMAT_WEEK_CHINESE_SIMPLE[intWeekNum];
            }
        } catch (Exception ex) {
            strResult = " ";
        }
        return strResult;
    }

    /**
     * 获取当前月天数
     *
     * @return
     */
    public static int getCurrentMonthDays() {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.DATE, 1);// 把日期设置为当月第一天
        a.roll(Calendar.DATE, -1);// 日期回滚一天，也就是最后一天
        return a.get(Calendar.DATE);
    }

    /**
     * 判断当前时间是否在两个时间之间(区间都不包含)
     *
     * @param startTime 开始时间 （格式yyyyMMdd24HHmmss）20160229160354
     * @param endTime   结束时间（格式yyyyMMdd24HHmmss）20160229160354
     * @return
     * @Auth NZF 2016-02-29
     */
    public static boolean isBetweenTwoTimes(String startTime, String endTime) {
        //当前时间
        long nowTime = Long.parseLong(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
        if (ObjectUtils.isEmpty(startTime) || ObjectUtils.isEmpty(endTime)) {
            return false;
        }
        return Long.parseLong(startTime) < nowTime && nowTime < Long.parseLong(endTime);
    }

    /**
     * 17位格式判断当前时间是否在两个时间之间(区间都不包含)
     *
     * @param startTime 开始时间 （格式yyyyMMddHHmmssS）20160724111924116
     * @param endTime   结束时间（格式yyyyMMdd24HHmmss）20160724111924116
     * @return
     * @Auth NZF 2016-02-29
     */
    public static boolean isBetweenTwoTimes17(String startTime, String endTime) {
        //当前时间
        long nowTime = Long.parseLong(getTodayChar17());
        if (ObjectUtils.isEmpty(startTime) || ObjectUtils.isEmpty(endTime)) {
            return false;
        }
        return Long.parseLong(startTime) < nowTime && nowTime < Long.parseLong(endTime);
    }


    /**
     * @return boolean
     * @Author Wuyongsheng
     * @Description //判断当前时间是否在制定时间之后
     * @Date 10:52 2019/7/18
     * @Param [oneTime]
     **/
    public static boolean isAfterOneTime(String oneTime) {
        //当前时间
        long nowTime = Long.parseLong(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
        if (ObjectUtils.isEmpty(oneTime)) {
            return false;
        }
        return nowTime > Long.parseLong(oneTime);
    }

    /**
     * 判断当前时间是否在制定时间之后
     *
     * @param oneTime 结束时间（格式yyyyMMdd24HHmmss）20160229160354
     * @return
     * @Auth NZF 2016-02-29
     */
    public static boolean isAfterOneTime17(String oneTime) {
        //当前时间
        long nowTime = Long.parseLong(getTodayChar17());
        if (ObjectUtils.isEmpty(oneTime)) {
            return false;
        }
        return nowTime > Long.parseLong(oneTime);
    }


    /**
     * @return boolean
     * @Author Wuyongsheng
     * @Description //判断当前时间是否在制定时间之前
     * @Date 10:53 2019/7/18
     * @Param [oneTime]
     **/
    public static boolean isBeforeOneTime(String oneTime) {
        //当前时间
        long nowTime = Long.parseLong(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
        if (ObjectUtils.isEmpty(oneTime)) {
            return false;
        }
        return nowTime < Long.parseLong(oneTime);
    }

    /**
     * 判断当前时间是否在制定时间之前
     *
     * @param oneTime 结束时间（格式yyyyMMdd24HHmmss）20160229160354
     * @return
     * @Auth NZF 2016-02-29
     */
    public static boolean isBeforeOneTime17(String oneTime) {
        //当前时间
        long nowTime = Long.parseLong(getTodayChar17());
        if (ObjectUtils.isEmpty(oneTime)) {
            return false;
        }
        return nowTime < Long.parseLong(oneTime);
    }

    /*
     * 设置有效时间至次日00：05：00
     */
    public static long getTodayExpireTime() {
        Calendar calendar = Calendar.getInstance();
        String date = DateTimeUtil.getTodayChar8();
        calendar.set(Calendar.YEAR, Integer.parseInt(date.substring(0, 4)));
        calendar.set(Calendar.MONTH, Integer.parseInt(date.substring(4, 6)) - 1);
        calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date.substring(6, 8)) + 1);
        calendar.set(Calendar.HOUR_OF_DAY, 00);
        calendar.set(Calendar.MINUTE, 05);
        calendar.set(Calendar.SECOND, 00);

        Calendar ccalendar = Calendar.getInstance();// 当前时间
        ccalendar.setTime(new Date());
        return calendar.getTimeInMillis() - ccalendar.getTimeInMillis();
    }

    /**
     * 失效时间至月底
     *
     * @return
     */
    public static long getMonthExpireTime() {
        Calendar calendar = Calendar.getInstance();
        String date = DateTimeUtil.getTodayChar8();
        calendar.set(Calendar.YEAR, Integer.parseInt(date.substring(0, 4)));
        calendar.set(Calendar.MONTH, Integer.parseInt(date.substring(4, 6)) - 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);

        Calendar ccalendar = Calendar.getInstance();// 当前时间
        ccalendar.setTime(new Date());
        return calendar.getTimeInMillis() - ccalendar.getTimeInMillis();
    }

    /**
     * 永久有效(方法中实现使用1年有效时长)
     *
     * @return
     */
    public static long getOneYearExpireTime() {
        Calendar calendar = Calendar.getInstance();
        String date = DateTimeUtil.getTodayChar8();
        calendar.set(Calendar.YEAR, Integer.parseInt(date.substring(0, 4)) + 1);
        calendar.set(Calendar.MONTH, Integer.parseInt(date.substring(4, 6)) - 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, 00);
        calendar.set(Calendar.MINUTE, 00);
        calendar.set(Calendar.SECOND, 00);

        Calendar ccalendar = Calendar.getInstance();// 当前时间
        ccalendar.setTime(new Date());
        return calendar.getTimeInMillis() - ccalendar.getTimeInMillis();
    }

    /**
     * 进行时间的大小比较,比较大
     *
     * @param tim1 比对的时间1
     * @param tim2 比对的时间2
     * @return 如果时间tim1大于或者等于time2返回为true
     */
    public static boolean TimeCompare(String tim1, String tim2) {
        if (tim1 == null || "".equals(tim1) || tim2 == null || "".equals(tim2)) {
            return false;
        }
        // 检查并将其格式修改正确
        String onTime1 = checkAndMend(tim1);
        String onTime2 = checkAndMend(tim2);
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            cal1.setTime(sdf.parse(onTime1));
            cal2.setTime(sdf.parse(onTime2));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 如果时间time1小于time2返回为true,
        return cal1.getTime().getTime() >= cal2.getTime().getTime();
    }

    /**
     * 检查其时间，如果时间并非14位表示，进行补序操作，如果超过14位，则进行去除多余的位     *
     *
     * @param time
     * @return 修改后的值
     */
    public static String checkAndMend(String time) {
        String onTime = time;
        // 如果当前当前时间格式长度大于14位，进行截取
        if (onTime.length() > 14) {
            onTime = onTime.substring(0, 14);
        }
        // 如果当前时间格式长度小于14则需要补0操作
        else if (onTime.length() < 14) {
            int getValue = 14 - onTime.length();

            onTime = onTime + addZone(getValue);
        }
        return onTime;
    }

    /**
     * 补0方法
     *
     * @param length 需要补0的方法
     * @return
     */
    public static String addZone(int length) {
        String value = "";
        for (int i = 0; i < length; i++) {
            value += "0";
        }
        return value;
    }

    public static int[] getNeturalAge(Calendar calendarBirth, Calendar calendarNow) {
        int diffYears;
        int diffMonths;
        int diffDays;
        int dayOfBirth = calendarBirth.get(Calendar.DAY_OF_MONTH);
        int dayOfNow = calendarNow.get(Calendar.DAY_OF_MONTH);
        if (dayOfBirth <= dayOfNow) {
            diffMonths = getMonthsOfAge(calendarBirth, calendarNow);
            diffDays = dayOfNow - dayOfBirth;
            if (diffMonths == 0)
                diffDays++;
        } else {
            if (isEndOfMonth(calendarBirth)) {
                if (isEndOfMonth(calendarNow)) {
                    diffMonths = getMonthsOfAge(calendarBirth, calendarNow);
                    diffDays = 0;
                } else {
                    calendarNow.add(Calendar.MONTH, -1);
                    diffMonths = getMonthsOfAge(calendarBirth, calendarNow);
                    diffDays = dayOfNow + 1;
                }
            } else {
                if (isEndOfMonth(calendarNow)) {
                    diffMonths = getMonthsOfAge(calendarBirth, calendarNow);
                    diffDays = 0;
                } else {
                    calendarNow.add(Calendar.MONTH, -1);// 上个月
                    diffMonths = getMonthsOfAge(calendarBirth, calendarNow);
                    // 获取上个月最大的一天
                    int maxDayOfLastMonth = calendarNow.getActualMaximum(Calendar.DAY_OF_MONTH);
                    if (maxDayOfLastMonth > dayOfBirth) {
                        diffDays = maxDayOfLastMonth - dayOfBirth + dayOfNow;
                    } else {
                        diffDays = dayOfNow;
                    }
                }
            }
        }
        // 计算月份时，没有考虑年
        diffYears = diffMonths / 12;
        diffMonths = diffMonths % 12;
        return new int[]{diffYears, diffMonths, diffDays};
    }

    /**
     * 获取两个日历的月份之差
     *
     * @param calendarBirth
     * @param calendarNow
     * @return
     */
    public static int getMonthsOfAge(Calendar calendarBirth,
                                     Calendar calendarNow) {
        return (calendarNow.get(Calendar.YEAR) - calendarBirth
                .get(Calendar.YEAR)) * 12 + calendarNow.get(Calendar.MONTH)
                - calendarBirth.get(Calendar.MONTH);
    }

    /**
     * 判断这一天是否是月底
     *
     * @param calendar
     * @return
     */
    public static boolean isEndOfMonth(Calendar calendar) {
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        return dayOfMonth == calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 计算某时间与当前时间之间的天数差
     *
     * @param fromDate
     * @return
     */
    public static int getIntervalDays(Date fromDate) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(fromDate);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Calendar now = Calendar.getInstance();
        now.set(Calendar.HOUR_OF_DAY, 0);
        now.set(Calendar.MINUTE, 0);
        now.set(Calendar.SECOND, 0);
        long interval = now.getTimeInMillis() - cal.getTimeInMillis();
        long syts = interval / 60 / 60 / 1000 / 24;// 获取今天到指定日期剩余天数
        return (int) syts;
    }

    /**
     * yyyyMMddHHmmss => yyyy-MM-dd
     *
     * @param dateTime
     * @return
     */
    public static String getFomateDate(String dateTime) {
        try {
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = dateFormat1.parse(dateTime);
            return dateFormat.format(date);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * @param dateTime
     * @return String
     * @desc yyyy-MM-dd hh:mm:ss --> yyyyMMddHHmmss
     * @author: Wuys <272600258@qq.com>
     * @createTime: 2017年7月19日 下午2:37:07
     * @history:
     */
    public static String getFomateDate14(String dateTime) {
        try {
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date date = dateFormat.parse(dateTime);
            return dateFormat1.format(date);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * @param dateStr (yyyy-MM-dd)
     * @return String
     * @desc yyyy-MM-dd => yyyyMMddHHmmss
     * @author: Wuys <272600258@qq.com>
     * @createTime: 2017年6月15日 下午7:35:34
     * @history:
     */
    public static String toFormatDate14(String dateStr) {
        if (!ObjectUtils.isEmpty(dateStr)) {
            String fDate = "";
            String pattern = "[1-9]\\d{3}-((0\\d)|(1[0-2]))-(([0|1|2]\\d)|3[0-1])";
            //yyyy-MM-dd hh:mm:ss

            if (Pattern.matches(pattern, dateStr)) {
                fDate = dateStr.trim().replaceAll("-", "").concat("000000");
            } else {
                fDate = dateStr.trim().substring(0, dateStr.trim().length() >= 17 ? 17 : dateStr.trim().length());
            }
            return fDate;
        } else {
            return "";
        }
    }

    /**
     * beforeFomate => afterFomate
     *
     * @param beforeFomate
     * @param afterFomate
     * @param dateTime
     * @return
     */
    public static String coverFormate(String beforeFomate, String afterFomate, String dateTime) {
        try {
            SimpleDateFormat dateFormat1 = new SimpleDateFormat(beforeFomate);
            SimpleDateFormat dateFormat = new SimpleDateFormat(afterFomate);
            Date date = dateFormat1.parse(dateTime);
            return dateFormat.format(date);

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

}
